"""
Copyright (c) 2009 Twilio, Inc.

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
"""

import urllib, urllib2, base64

try:
    from google.appengine.api import urlfetch
    APPENGINE = True
except:
    APPENGINE = False

_TWILIO_API_URL = 'https://api.twilio.com'

class HTTPErrorProcessor(urllib2.HTTPErrorProcessor):
    def https_response(self, request, response):
        code, msg, hdrs = response.code, response.msg, response.info()
        if code >= 300:
            response = self.parent.error(
                'http', request, response, code, msg, hdrs)
        return response

class HTTPErrorAppEngine(Exception): pass

class TwilioRequest(urllib2.Request):
    def get_method(self):
        if getattr(self, 'http_method', None):
            return self.http_method
        return urllib2.Request.get_method(self)

class Account:
    """Twilio account object.  Can be used to initiate outgoing calls, ....
    """
    def __init__(self, id, token):
        """initialize a twilio account object
        
        id: Twilio account SID/ID
        token: Twilio account token
        
        returns a Twilio account object
        """
        self.id = id
        self.token = token
        self.opener = None
    
    def _build_get_uri(self, uri, params):
        if params and len(params) > 0:
            if uri.find('?') > 0:
                if uri[-1] != '&':
                    uri += '&'
                uri = uri + urllib.urlencode(params)
            else:
                uri = uri + '?' + urllib.urlencode(params)
        return uri
    
    def _urllib2_fetch(self, uri, params, method=None):
        # install error processor to handle HTTP 201 response correctly
        if self.opener == None:
            self.opener = urllib2.build_opener(HTTPErrorProcessor)
            urllib2.install_opener(self.opener)
        
        if method and method == 'GET':
            uri = self._build_get_uri(uri, params)
            req = TwilioRequest(uri)
        else:
            req = TwilioRequest(uri, urllib.urlencode(params))
            if method and (method == 'DELETE' or method == 'PUT'):
                req.http_method = method
        
        authstring = base64.encodestring('%s:%s' % (self.id, self.token))
        authstring = authstring.replace('\n', '')
        req.add_header("Authorization", "Basic %s" % authstring)
        
        response = urllib2.urlopen(req)
        return response.read()
    
    def _appengine_fetch(self, uri, params, method):
        if method == 'GET':
            uri = self._build_get_uri(uri, params)
        
        try:
            httpmethod = getattr(urlfetch, method)
        except AttributeError:
            raise NotImplementedError(
                "Google App Engine does not support method '%s'" % method)
        
        authstring = base64.encodestring('%s:%s' % (self.id, self.token))
        authstring = authstring.replace('\n', '')
        r = urlfetch.fetch(url=uri, payload=urllib.urlencode(params),
            method=httpmethod,
            headers={'Content-Type': 'application/x-www-form-urlencoded',
                'Authorization': 'Basic %s' % authstring})
        if r.status_code >= 300:
            raise HTTPErrorAppEngine("HTTP %s: %s" % \
                (r.status_code, r.content))
        return r.content
    
    def request(self, path, method=None, vars={}):
        """sends a request and gets a response from the Twilio REST API
        
        path: the URL (relative to the endpoint URL, after the /v1
        url: the HTTP method to use, defaults to POST
        vars: for POST or PUT, a dict of data to send
        
        returns Twilio response in XML or raises an exception on error
        """
        if not path or len(path) < 1:
            raise ValueError('Invalid path parameter')
        if method and method not in ['GET', 'POST', 'DELETE', 'PUT']:
            raise NotImplementedError(
                'HTTP %s method not implemented' % method)
        
        if path[0] == '/':
            uri = _TWILIO_API_URL + path
        else:
            uri = _TWILIO_API_URL + '/' + path
        
        if APPENGINE:
            return self._appengine_fetch(uri, vars, method)
        return self._urllib2_fetch(uri, vars, method)
